import React, { useRef, useEffect } from 'react';
import HTMLViewer from '@metacell/geppetto-meta-ui/html-viewer/HTMLViewer';
import { CircularProgress, Box } from '@mui/material';
import { primaryColor } from '../../theme';

interface CustomHTMLViewerProps {
  content?: string;
  id?: string;
  style?: React.CSSProperties;
}

const CustomHTMLViewer: React.FC<CustomHTMLViewerProps> = ({ content, id, style }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const dimensionsRef = useRef({ width: 200, height: 200 });

  const getParentSize = (): DOMRect | false => {
    if (!containerRef.current?.parentNode) {
      return false;
    }
    return (containerRef.current.parentNode as HTMLElement).getBoundingClientRect();
  };

  const getSvgComponent = (): SVGElement | null => {
    // svg element
    return containerRef.current?.children[0]?.children[0]?.children[0] as SVGElement || null;
  };

  const wasParentResized = (dimensions: DOMRect): boolean => {
    return (
      dimensions.width !== dimensionsRef.current.width ||
      dimensions.height !== dimensionsRef.current.height
    );
  };

  const adjustSVGSize = (): void => {
    const svg = getSvgComponent();
    if (svg) {
      const width = (dimensionsRef.current.width - 20) > 0
        ? `${dimensionsRef.current.width - 20}px`
        : '0px';
      const height = (dimensionsRef.current.height - 20) > 0
        ? `${dimensionsRef.current.height - 20}px`
        : '0px';
      svg.removeAttribute('width');
      svg.removeAttribute('height');
      svg.setAttribute('width', width);
      svg.setAttribute('height', height);
    }
  };

  const resizeIfNeeded = (force = false): void => {
    const dimensions = getParentSize();

    if (dimensions !== false && (wasParentResized(dimensions) || force)) {
      dimensionsRef.current = {
        width: dimensions.width,
        height: dimensions.height,
      };
      adjustSVGSize();
    }
  };

  const delayedResize = (): void => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
    timerRef.current = setTimeout(() => resizeIfNeeded(), 100);
  };

  useEffect(() => {
    window.addEventListener('resize', delayedResize);
    resizeIfNeeded(true);

    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
      window.removeEventListener('resize', delayedResize);
    };
  }, []);

  useEffect(() => {
    resizeIfNeeded(true);
  });

  if (content === undefined) {
    return (
      <CircularProgress
        sx={{
          color: primaryColor,
          position: 'absolute',
          margin: 'auto',
          top: '50%',
          left: '50%',
        }}
      />
    );
  }

  return (
    <Box
      id="plot"
      ref={containerRef}
      sx={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'inherit',
      }}
    >
      <HTMLViewer content={content} id={id} style={{ backgroundColor: 'inherit', ...style }} />
    </Box>
  );
};

export default CustomHTMLViewer;

